const BASE_URL = 'http://127.0.0.1:8080';

const request = (url, method = 'GET', data = null, needToken = false) => {
  return new Promise((resolve, reject) => {
    const headers = {
      'Content-Type': 'application/json'
    };

    if (needToken) {
      const token = uni.getStorageSync('token');
      if (token) {
        headers['Authorization'] = 'Bearer ' + token;
      }
    }

    // 🔥 调试日志
    console.log('[API] 请求:', method, BASE_URL + url, data);

    uni.request({
      url: BASE_URL + url,
      method,
      data,
      header: headers,
      success: (res) => {
        console.log('[API] 响应:', res);
        const { statusCode, data } = res;

        if (statusCode >= 200 && statusCode < 300) {
          resolve(data);
        } else if (statusCode === 401) {
          uni.clearStorageSync();
          uni.showToast({ title: '登录已失效', icon: 'none' });
          uni.reLaunch({ url: '/pages/njt/user_register' });
          reject(new Error('未授权'));
        } else {
          uni.showToast({ title: data.msg || '请求失败', icon: 'none' });
          reject(new Error(data.msg || '请求异常'));
        }
      },
      fail: (err) => {
        console.error('[API] 网络错误:', err);
        uni.showToast({ title: '网络连接失败', icon: 'none' });
        reject(err);
      }
    });
  });
};

const get = (url, needToken = false) => {
  return request(url, 'GET', null, needToken);
};

// ✅ 修复：data 默认为 {}
const post = (url, data = {}, needToken = false) => {
  return request(url, 'POST', data, needToken);
};

const put = (url, data = {}, needToken = false) => {
  return request(url, 'PUT', data, needToken);
};

const del = (url, needToken = false) => {
  return request(url, 'DELETE', null, needToken);
};

export { get, post, put, del };